//
//  WBUserAccountViewModel.swift
//  weibo
//
//  Created by yanghong on 15/12/8.
//  Copyright © 2015年 杨鸿. All rights reserved.
//

import  UIKit

class WBUserAccountViewModel  {
    
    var userAccount: WBUserAccount?
    
    //归档和解档的路径
    var archivePath:String = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("useraccount.archive")
    //判断是否登录
    var userLogon: Bool {
        
        // print(accessToken)
        
        return accessToken != nil
        
    }
    //只读属性
    var accessToken: String? {
        //取出userAccount 里面的 accessToken并且判断是否过期 没有过期则返回accessToken
        if let accessToken = userAccount?.access_token where !isExperies {
            
            return accessToken
        }
        
        return nil
        
    }
    //
    var isExperies: Bool {
        // 如果
        guard let experiesDate = userAccount?.expiresDate else {
            
            return true
        }
        
        if NSDate().compare(experiesDate) == NSComparisonResult.OrderedAscending {
            return false
            
        }
        return true
    }
    
    /**
     
     在这个类里面主要是处理关于请求回来数据的逻辑
     - 保存请求回来的用户信息
     - 在这里发送网络请求
     
     */
     
     //设置一个单例,作为全局访问点
    
    static var sharedAccount: WBUserAccountViewModel = WBUserAccountViewModel()
    
    private init() {
     
        userAccount = loadUserAccount()
    
    }
    
}
// MARK -  发送网络请求
extension WBUserAccountViewModel {
    
    func loadAccessToken(code: String, complet: (isSuccessed: Bool)->()) {
        //在这里调用网络工具类发送请求的方法
        
        WBNetworkingTools.shareNetworking.loadAccessToken(code) { (response, error) -> () in
            
            if error != nil {
                
                print("请求错误\(error)")
                //如果请求错误,那么返回 false
                complet(isSuccessed: false)
                
            }
            guard let dict = response as? [String: AnyObject] else {
                
                return
            }
            //如果返回的是一个字典,就把数据存储在模型里面
            let account = WBUserAccount(dict: dict)
            
            self.userAccount = account
            
            self.loadUserInfo(account.uid!, accessToken: account.access_token!, complete: complet)
            
        }
        
    }
    // 请求用户数据
    private func loadUserInfo(uid: String, accessToken: String, complete: (isSuccessed: Bool)->()) {
        
        WBNetworkingTools.shareNetworking.loadUserInfo(uid, accessToken: accessToken) { (response, error) -> () in
            
            if error != nil {
                
                print(error)
                
                complete(isSuccessed: false)
                return
            }
            print(response)
            
            guard let responseDict = response as? [String: AnyObject] else {
                
                return
                
            }
            
            self.userAccount?.avatar_large = responseDict["avatar_large"] as? String
            self.userAccount?.screen_name = responseDict["screen_name"] as? String
            self.saveAccount(self.userAccount!)
            complete(isSuccessed: true)
        }
    }
}
// 用户信息的归档和解档
extension WBUserAccountViewModel {
    //归档
    func saveAccount(account: WBUserAccount) {
    
    NSKeyedArchiver.archiveRootObject(account, toFile: archivePath)
    
    }
     //解档
    func loadUserAccount()->WBUserAccount? {
    
     return   NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath) as? WBUserAccount
        
    }

}